from flask import Blueprint, request, jsonify
from ..models import Salary, Employee
from .. import db
from datetime import datetime
from decimal import Decimal

bp = Blueprint('salary', __name__, url_prefix='/api/salaries')

@bp.route('/', methods=['GET'])
def get_salaries():
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    year = request.args.get('year', type=int)
    month = request.args.get('month', type=int)
    employee_id = request.args.get('employee_id', type=int)
    department_id = request.args.get('department_id', type=int)
    
    # 构建查询
    query = Salary.query.join(Employee)
    
    if year:
        query = query.filter(Salary.year == year)
    if month:
        query = query.filter(Salary.month == month)
    if employee_id:
        query = query.filter(Salary.employee_id == employee_id)
    if department_id:
        query = query.filter(Employee.department_id == department_id)
    
    # 执行分页查询
    pagination = query.order_by(Salary.year.desc(), Salary.month.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    salaries = pagination.items
    
    return jsonify({
        'items': [{
            'id': salary.id,
            'employee_id': salary.employee_id,
            'employee_name': salary.employee.name,
            'department_name': salary.employee.department.name if salary.employee.department else None,
            'year': salary.year,
            'month': salary.month,
            'base_salary': float(salary.base_salary),
            'bonus': float(salary.bonus),
            'overtime_pay': float(salary.overtime_pay),
            'deductions': float(salary.deductions),
            'total_salary': float(salary.total_salary),
            'payment_date': salary.payment_date.strftime('%Y-%m-%d') if salary.payment_date else None,
            'status': salary.status
        } for salary in salaries],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': page
    })

@bp.route('/<int:id>', methods=['GET'])
def get_salary(id):
    salary = Salary.query.get_or_404(id)
    return jsonify({
        'id': salary.id,
        'employee_id': salary.employee_id,
        'employee_name': salary.employee.name,
        'department_name': salary.employee.department.name if salary.employee.department else None,
        'year': salary.year,
        'month': salary.month,
        'base_salary': float(salary.base_salary),
        'bonus': float(salary.bonus),
        'overtime_pay': float(salary.overtime_pay),
        'deductions': float(salary.deductions),
        'total_salary': float(salary.total_salary),
        'payment_date': salary.payment_date.strftime('%Y-%m-%d') if salary.payment_date else None,
        'status': salary.status
    })

@bp.route('/', methods=['POST'])
def create_salary():
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['employee_id', 'year', 'month', 'base_salary']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'缺少必填字段: {field}'}), 400
    
    # 检查员工是否存在
    employee = Employee.query.get(data['employee_id'])
    if not employee:
        return jsonify({'error': '员工不存在'}), 400
    
    # 检查是否已存在该月的工资记录
    existing = Salary.query.filter_by(
        employee_id=data['employee_id'],
        year=data['year'],
        month=data['month']
    ).first()
    if existing:
        return jsonify({'error': '该员工该月的工资记录已存在'}), 400
    
    # 计算总工资
    base_salary = Decimal(str(data['base_salary']))
    bonus = Decimal(str(data.get('bonus', 0)))
    overtime_pay = Decimal(str(data.get('overtime_pay', 0)))
    deductions = Decimal(str(data.get('deductions', 0)))
    total_salary = base_salary + bonus + overtime_pay - deductions
    
    # 创建工资记录
    salary = Salary(
        employee_id=data['employee_id'],
        year=data['year'],
        month=data['month'],
        base_salary=base_salary,
        bonus=bonus,
        overtime_pay=overtime_pay,
        deductions=deductions,
        total_salary=total_salary,
        payment_date=datetime.strptime(data['payment_date'], '%Y-%m-%d') if data.get('payment_date') else None,
        status=data.get('status', '未发放')
    )
    
    db.session.add(salary)
    db.session.commit()
    
    return jsonify({
        'message': '工资记录创建成功',
        'id': salary.id
    }), 201

@bp.route('/<int:id>', methods=['PUT'])
def update_salary(id):
    salary = Salary.query.get_or_404(id)
    data = request.get_json()
    
    # 更新工资信息
    if 'base_salary' in data:
        salary.base_salary = Decimal(str(data['base_salary']))
    if 'bonus' in data:
        salary.bonus = Decimal(str(data['bonus']))
    if 'overtime_pay' in data:
        salary.overtime_pay = Decimal(str(data['overtime_pay']))
    if 'deductions' in data:
        salary.deductions = Decimal(str(data['deductions']))
    if 'payment_date' in data:
        salary.payment_date = datetime.strptime(data['payment_date'], '%Y-%m-%d')
    if 'status' in data:
        salary.status = data['status']
    
    # 重新计算总工资
    salary.total_salary = (
        salary.base_salary +
        salary.bonus +
        salary.overtime_pay -
        salary.deductions
    )
    
    db.session.commit()
    
    return jsonify({
        'message': '工资记录更新成功'
    })

@bp.route('/<int:id>', methods=['DELETE'])
def delete_salary(id):
    salary = Salary.query.get_or_404(id)
    
    # 检查是否已发放
    if salary.status == '已发放':
        return jsonify({'error': '已发放的工资记录无法删除'}), 400
    
    db.session.delete(salary)
    db.session.commit()
    
    return jsonify({
        'message': '工资记录删除成功'
    }) 